package com.vsclouds.mp.util;

import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * Created with Software Dept.
 * <p> {@code ResponseDataFactory}
 * 响应数据生产类
 *
 * @author : tianbaolei
 * @date : 2020-06-17 16:28
 * Description:
 */
public class ResponseDataFactory {

    static final HashMap EMPTY = new HashMap(2);

    public static <T> ResponseData<T> success(HttpServletResponse response) {
        ResponseHandler.handle(response, HttpStatus.OK);
        return success(response, null);
    }

    public static <T> ResponseData<T> success(HttpServletResponse response, T data) {
        ResponseHandler.handle(response, HttpStatus.OK);
        return getResponseData(ResultCode.R_OPERATION_SUCCESS.value(),
                ResultCode.R_OPERATION_SUCCESS.getDescription(),
                data);
    }

    public static <T> ResponseData<T> badRequest(HttpServletResponse response) {
        ResponseHandler.handle(response, HttpStatus.BAD_REQUEST);
        return getResponseData(ResultCode.R_BAD_REQUEST.value(),
                ResultCode.R_BAD_REQUEST.getDescription(),
                null);
    }

    public static <T> ResponseData<T> getResponseData(ResultCode resultCode) {
        return getResponseData(resultCode.value(), resultCode.getDescription(), null);
    }

    public static <T> ResponseData<T> getResponseData(ResultCode resultCode, T data) {
        return getResponseData(resultCode.value(), resultCode.getDescription(), data);
    }

    public static <T> ResponseData<T> getResponseData(int resultCode, String message, T data) {
        ResponseData<T> responseData = new ResponseData<>();
        responseData.setStatus(HttpStatus.OK.value());
        responseData.setResultCode(resultCode);
        responseData.setMessage(message);
        responseData.setData(data == null ? (T) EMPTY : data);
        return responseData;
    }
}
